<template>
  <div>
    <el-upload
  class="avatar-uploader"
  action="http://localhost:9191/avatar"
  :headers="{token:Token}"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
  :on-error="ErrorMsg">
  <img v-if="imageUrl" :src="`http://localhost:9191${imageUrl}`" class="avatar">
  <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
  <el-button @click="PostUser">确认更改</el-button>
</el-upload>
  </div>
</template>

<script setup>
import { inject, ref } from "vue";
import {Plus} from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";

const $axios = inject('$axios');
//上传成功的头像地址
let imageUrl =ref('')
//获取本地存储内的token值
    let user = JSON.parse(localStorage.getItem('user'))
    let Token = ref(user.token)

//请求登录者的个人基本信息
const GetUerInfo =()=>{
    //获取当前登录者的账号
    let user = JSON.parse(localStorage.getItem('user'))
    //拼接请求地址
    let url = '/userinfo/'+user.username;
    //请求个人信息
    $axios.get(url).then((res)=>{
        if(res.code === '200'){
            //先显示原来的头像
            if(res.data.avatarUrl){
                imageUrl.value = res.data.avatarUrl
            }
        }
        
    }).catch((err)=>{
        console.log(err);
        
    })
}
//调用请求函数
GetUerInfo();

//创建函数：验证当前上传的文件是图片文件
const beforeAvatarUpload = (file)=>{
    //png,jpg,jpeg
    switch(file.type){
        case 'image/jpg':
        case 'image/png':
        case 'image/jpeg':
            //继续上传图片
        return true;

        default:
            ElMessage.error('上传的文件必须是图片类型')
            //终止上传图片
            return false;
    }
    
}

//创建函数：获取上传成功后的存储到数据表中的图片地址
//将图片上传到指定的后端地址，完成处理后返回的结果
const handleAvatarSuccess = (res)=>{
    if(res.code === '200'){
       imageUrl.value = res.data 
    }     
}
    

//上传失败
const ErrorMsg =(error)=>{
    console.log(error);
    
}

//提交修改登录者个人接口信息
const PostUser=()=>{
    let data = {
        "id":1,
        "username":"admin",
        "nickname":"管理员",
        "email":"Admin123@qq.com",
        "phone":"13672872006",
        "address":"广东省广州市白云区",
        "avatarUrl":imageUrl.value,
        "role":"admin",
        "newPassword":null
    }
    $axios.post('/user',data).then((res)=>{
        console.log(res);
        GetUerInfo()
    }).catch(err=>{
        console.log(err);
        
    })
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>